import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { ReuseTabService, SimpleTableData, SimpleTableColumn, SimpleTableComponent } from '@delon/abc';
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { _HttpClient } from '@delon/theme';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { CourseService } from '../course.service';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.css']
})
export class DetailComponent implements OnInit {

  constructor(private reuseTabService: ReuseTabService,
              private http: _HttpClient,
              public msg: NzMessageService,
              private modalSrv: NzModalService,
              private fb: FormBuilder,
              private courseService: CourseService,
              private activatedRoute: ActivatedRoute,) { }

  courseId: any;

  ngOnInit() {
    this.reuseTabService.title = "资源管理-详情";

    this.form = this.fb.group({
      name: [null, [Validators.required]],
      resourceUrl: [null, [Validators.required]],
      detail: [null, [Validators.required]],
      tryout: [null, [Validators.required]],
      sequence: [null, [Validators.required]],
      playTime: [null, []],
    });

    let temp: any = localStorage.getItem("employee");
    this._employee = JSON.parse(temp);

    // this.courseService.getValueListByParentCode("courseType").subscribe(resp => {
    //   if (resp.success)
    //     this.courseTypeList = resp.data;
    // });

    this.activatedRoute.queryParams.subscribe(params => {
      console.log(params);
      this.courseId = params["id"];
      this.getData();
    });
  }

  detail(item: any): any {
    
  }

  q: any = {
    pi: 1,
    ps: 10,
    sorter: '',
    status: null,
    statusList: [],
  };
  data: any[] = [];

  loading = false;
  status = [
    { index: 0, text: '关闭', value: false, type: 'default', checked: false },
    {
      index: 1,
      text: '运行中',
      value: false,
      type: 'processing',
      checked: false,
    },
    { index: 2, text: '已上线', value: false, type: 'success', checked: false },
    { index: 3, text: '异常', value: false, type: 'error', checked: false },
  ];

  @ViewChild('st') st: SimpleTableComponent;
  @ViewChild('modalContent') modalContent: TemplateRef<{}>;

  columns: SimpleTableColumn[] = [
    { title: '', index: 'key', type: 'checkbox' },
    { title: '名称', index: 'name' },
    { title: '试听', index: 'tryout' },
    { title: '播放次数', index: 'playTime' },
    { title: '显示顺序', index: 'sequence' },
    {
      title: '操作',
      buttons: [
        {
          text: '编辑',
          click: (item: any) => this.edit(this.modalContent, item),
        },
        {
          text: '删除',
          click: (item: any) => this.delete(item),
        },
      ],
    },
  ];

  selectedRows: SimpleTableData[] = [];
  description = '';
  totalCallNo = 0;
  expandForm = false;

  form: FormGroup;
  _employee: any;
  fromList: any;
  statusList: any;
  courseTypeList: any;

  getData() {
    this.loading = true;
    this.q.statusList = this.status
      .filter(w => w.checked)
      .map(item => item.index);
    if (this.q.status !== null && this.q.status > -1)
      this.q.statusList.push(this.q.status);

    this.courseService.queryCourseDetailById(this.courseId).subscribe(resp => {
      this.loading = false;
      if (resp.success)
        this.data = resp.data;
      else
        this.data = [];

    }, error => {
      this.loading = false;
      this.msg.error("error: " + JSON.stringify(error));

    });

  }

  checkboxChange(list: SimpleTableData[]) {
    this.selectedRows = list;
    this.totalCallNo = this.selectedRows.reduce(
      (total, cv) => total + cv.callNo,
      0,
    );
  }

  remove() {
    this.http
      .delete('/rule', { nos: this.selectedRows.map(i => i.no).join(',') })
      .subscribe(() => {
        this.getData();
        this.st.clearCheck();
      });
  }

  add(tpl: TemplateRef<{}>) {
    this.form.reset();

    this.modalSrv.create({
      nzWidth: 1024,
      nzMaskClosable: false,
      nzTitle: '新建',
      nzContent: tpl,
      nzOkText: "提交",
      nzOnOk: () => {
        for (const i in this.form.controls) {
          this.form.controls[i].markAsDirty();
          this.form.controls[i].updateValueAndValidity();
        }
        if (this.form.invalid) return false;

        this.loading = true;
        this.courseService.create4CourseDetail(this.form.value, this.courseId).subscribe(resp => {
          this.loading = false;
          if (resp.success) {
            this.msg.success("操作成功");
            this.getData();
          }
          else
            this.msg.error(resp.errorMsg);

        }, error => {
          this.loading = false;
          this.msg.error("异常: " + JSON.stringify(error));

        });

        return false;
      },
      nzCancelText: null
    });
  }

  reset(ls: any[]) {
    for (const item of ls) item.value = false;
    this.getData();
  }

  edit(tpl: TemplateRef<{}>, item: any) {
    this.form.reset();
    this.form.patchValue({
      name: item.name,
      resourceUrl: item.resourceUrl,
      detail: item.detail,
      tryout: item.tryout,
      sequence: item.sequence,
      playTime: item.playTime,
    });

    this.modalSrv.create({
      nzWidth: 1024,
      nzMaskClosable: false,
      nzTitle: '编辑',
      nzContent: tpl,
      nzOkText: "保存",
      nzOnOk: () => {
        for (const i in this.form.controls) {
          this.form.controls[i].markAsDirty();
          this.form.controls[i].updateValueAndValidity();
        }
        if (this.form.invalid) return false;

        item.name = this.form.value.name;
        item.resourceUrl = this.form.value.resourceUrl;
        item.detail = this.form.value.detail;
        item.tryout = this.form.value.tryout;
        item.sequence = this.form.value.sequence;
        item.playTime = this.form.value.playTime;

        this.loading = true;
        this.courseService.edit4CourseDetail(item).subscribe(resp => {
          this.loading = false;
          if (resp.success) {
            this.msg.success("操作成功");
            this.getData();
          }
          else
            this.msg.error(resp.errorMsg);

        }, error => {
          this.loading = false;
          this.msg.error("异常: " + JSON.stringify(error));

        });

        return false;
      },
      nzCancelText: null
    });
  }

  delete(item: any): any {
    this.modalSrv.confirm({
      nzTitle: '确认删除么?',
      nzContent: '点击确认，继续删除。点击取消，退出操作！',
      nzOkText: "确定",
      nzCancelText: "取消",
      nzOnOk: () => {
        this.courseService.del4CourseDetail(item.id).subscribe(resp => {
          if (resp.success) {
            this.msg.success("操作成功");
            this.getData();
          }
          else
            this.msg.error(resp.errorMsg);
        }, error => {
          this.msg.error("异常: " + JSON.stringify(error));
        });
      }
    });

  }

  export(tpl: TemplateRef<{}>) {
    this.modalSrv.create({
      // nzWidth: 320,
      nzMaskClosable: false,
      nzTitle: '导入',
      nzContent: tpl,
      nzOkText: "提交",
      nzOnOk: () => {

        return false;
      },
      nzCancelText: null
    });
  }

}
